Example 1:
from typing import List, Optional
def myfunc() -> List[Optional[str]]:
some_list = [x for x in "abc"]
return some_list
Mypy complains on example 1:
Incompatible return value type (got "List[str]", expected "List[Optional[str]]")
However, this example gets no complaint:
Example 2:
def myfunc() -> List[Optional[str]]:
some_list = [x for x in "abc"]
return list(some_list)
What is the explanation for the inconsistent behavior?
Since in Python lists are invariant (see the examples here and here).
If we pass List[str] to someone that expects List[Optional[str]], that someone may add a None to our list and break our assumptions. The second example is valid however as the output of list() in the return statement is not saved anywhere and no one can depend on the the returned value being mutated illegally .